package com.example.mp4togift;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.adapters.VideoViewBindingAdapter;

import com.example.mp4togift.databinding.ActivityVideoBinding;
import com.example.mp4togift.has.GifExtractor;
import com.example.mp4togift.util.Glide4Engine;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.IncapableCause;
import com.zhihu.matisse.internal.entity.Item;

import java.io.File;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;

import io.reactivex.functions.Consumer;

/**
 * @author 林丹荣
 * 创建日期：2020/10/20
 * desc：视频截取帧动画操作
 */
public class VideoActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_CHOOSE = 23;
    private static final int REQUEST_CODE_CHOOSE_VIDEO = 101;
    private static final String TAG = "VideoActivity";

    private ActivityVideoBinding mActivityVideoBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initPermission();
        mActivityVideoBinding = DataBindingUtil.setContentView(this, R.layout.activity_video);
        mActivityVideoBinding.setOnclick(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_file_mp4:
                selectMedia(REQUEST_CODE_CHOOSE_VIDEO);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE_VIDEO && resultCode == RESULT_OK) {
            if (Matisse.obtainPathResult(data).size() > 0) {
                List<String> obtainPathResult = Matisse.obtainPathResult(data);
                String videoFilePath = obtainPathResult.get(0);
                transformGift(videoFilePath);
            }
        }
    }

    /**
     * mp4转gif
     * @param videoFilePath
     */
    long currentTime = 0;

    private void transformGift(final String videoFilePath) {
        Toast.makeText(this,"开始制作gif",Toast.LENGTH_SHORT).show();
        currentTime = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                startGIF(videoFilePath);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        double time =  (System.currentTimeMillis() - currentTime)/1000 ;
                        Toast.makeText(VideoActivity.this,"制作gif结束，耗时："+time,Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).start();
    }

    /**
     * 初始化权限
     */
    private void initPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);

        rxPermissions.request(
                Manifest.permission.CAMERA
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE
        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    //申请的权限全部允许
                    Toast.makeText(VideoActivity.this, "允许了权限!", Toast.LENGTH_SHORT).show();
                } else {
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(VideoActivity.this, "未授权权限，部分功能不能使用", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 选择视频或者图片
     *
     * @param requestCode
     */
    private void selectMedia(int requestCode) {
        if (requestCode == REQUEST_CODE_CHOOSE) {
            Matisse.from(VideoActivity.this)
                    .choose(MimeType.ofImage())
                    .showSingleMediaType(true)
                    .theme(R.style.Matisse_Zhihu)
                    .countable(false)
                    .maxSelectable(10)
                    .originalEnable(true)
                    .maxOriginalSize(10)
                    .imageEngine(new Glide4Engine())
                    .forResult(REQUEST_CODE_CHOOSE);

        } else if (requestCode == REQUEST_CODE_CHOOSE_VIDEO) {
            Matisse.from(VideoActivity.this)
                    .choose(MimeType.ofVideo())
                    .showSingleMediaType(true)
                    .theme(R.style.Matisse_Zhihu)
                    .countable(false)
                    .maxSelectable(1)
                    .originalEnable(true)
                    .maxOriginalSize(10)
                    .imageEngine(new Glide4Engine())
                    .addFilter(new Filter() {
                        @Override
                        protected Set<MimeType> constraintTypes() {
                            return new HashSet<MimeType>() {{
                                add(MimeType.MPEG);
                                add(MimeType.MP4);
                                add(MimeType.QUICKTIME);
                                add(MimeType.THREEGPP);
                                add(MimeType.THREEGPP2);
                                add(MimeType.MKV);
                                add(MimeType.WEBM);
                                add(MimeType.TS);
                                add(MimeType.AVI);
                            }};
                        }

                        @Override
                        public IncapableCause filter(Context context, Item item) {
                            if ((item.size >> 10) > (250 << 10) || item.duration > (2 * 60 * 1000)) {
                                return new IncapableCause("视频时长需小于2分钟，文件小于250M");
                            }
                            return null;
                        }
                    })
                    .forResult(REQUEST_CODE_CHOOSE_VIDEO);
        }
    }


    /***
     * 开始截图gif之类的功能
     */

    /**
     *作者:赵星海
     *时间:2019/4/23 10:06
     *用途: 开始生成GIF
     */
    private String Cover_puth = "";//封面地址
    private int TimeStart = 0;//Gif起始秒
    private int mAngle = 90; //视频旋转角度&封面旋转角度  // 一般是90度 后面会覆盖

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void startGIF(String videoFilePath) { // 开始转换GIF
        Log.i(TAG,"开始执行startGIF()");
        File sampleDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "存放GIF结果的文件夹");
        if (!sampleDir.exists()) {
            sampleDir.mkdirs();
        }
        File file = new File(sampleDir, new Date().getTime() + ".gif");
        Cover_puth = file.getAbsolutePath();
        try {
            // 获取视频信息
            MediaMetadataRetriever retr = new MediaMetadataRetriever();
            retr.setDataSource(videoFilePath);
            String rotation = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); // 视频旋转方向
            mAngle = Integer.parseInt(rotation.trim());
            Log.i(TAG,"视频方向获取 " + rotation);
        } catch (Exception e) {
            e.printStackTrace();
        }

        GifExtractor gifExtractor = new GifExtractor(this, videoFilePath, mAngle);
        gifExtractor.encoder(file.getAbsolutePath(), TimeStart * 1000, (TimeStart + 3) * 1000,
                10, 15);
    }

}
